package com.iseastar.guojiang.register;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.iseastar.BaseActivity2;
import com.iseastar.alipay.PayResult;
import com.iseastar.dianxiaosan.model.Const;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.UserBean;
import com.shb.model.OrderPayBean;
import com.shb.model.WxPayModel;
import com.shouhuobao.station.R;
import com.shouhuobao.station.wxapi.WXPayEntryActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**
 * 注册--------物料费用明细
 * Created by lidandan on 2018/5/2.
 */
public class RegisterMaterialPayActivity extends BaseActivity2 implements View.OnClickListener {
    private CheckBox mALiPayBox;
    private CheckBox mWeiXinBox;
    private UserBean userBean;
    private double deposit;
    private BroadcastReceiver wxCallBack;

    private final int SDK_PAY_FLAG = 3;
    private final int SDK_CHECK_FLAG = 4;

    private String orderId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        userBean = (UserBean) getIntent().getSerializableExtra("item");
        deposit = getIntent().getDoubleExtra("deposit", 0);
        if (userBean == null) {
            userBean = AppCache.getUser();
        }
        wxCallBack = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                showLoadingDialog(null);
                AppHttp.getInstance().courierPayCallBack(orderId, 1);
            }
        };
        IntentFilter intentFilter = new IntentFilter("courier_open_wxpay_callback");
        registerReceiver(wxCallBack, intentFilter);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.register_material_pay_activity);
        super.findViewById();
        getAppTitle().setCommonTitle("支付押金");
        TextView mMoneyTV = (TextView) findViewById(R.id.money_tv);
        mALiPayBox = (CheckBox) findViewById(R.id.ali_pay_box);
        mALiPayBox.setChecked(true);
        mWeiXinBox = (CheckBox) findViewById(R.id.weixin_pay_box);
        TextView payTV = (TextView) findViewById(R.id.pay_btn);
        payTV.setText("支付" + deposit + "元后，即可开通火箭侠");
        payTV.setOnClickListener(this);
        findViewById(R.id.ali_pay_ll).setOnClickListener(this);
        findViewById(R.id.weixin_pay_ll).setOnClickListener(this);
        mMoneyTV.setText(deposit + "元（可退）");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pay_btn:
                payMoney();
                break;
            case R.id.ali_pay_ll:
                mALiPayBox.setChecked(true);
                mWeiXinBox.setChecked(false);
                break;
            case R.id.weixin_pay_ll:
                mWeiXinBox.setChecked(true);
                mALiPayBox.setChecked(false);
                break;
        }
    }

    /**
     * 支付方法
     */
    public void payMoney() {
        if (mALiPayBox.isChecked()) {
            showLoadingDialog(null);
            AppHttp.getInstance().courierRegisterMateralPay(2);
        } else if (mWeiXinBox.isChecked()) {
            final IWXAPI wxapi = WXAPIFactory.createWXAPI(this, null);
            if (wxapi.isWXAppInstalled() == false) {
                showToast("未安装微信");
                return;
            }
            showLoadingDialog(null);
            WXPayEntryActivity.payFrom = 21;
            AppHttp.getInstance().courierRegisterMateralPay(1);
        } else {
            showToast("请选择支付方式");
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //微信支付返回
            case MsgID.courier_weixinPay:
                cancelLoadingDialog();
                ReqResult<WxPayModel> wxResult = JSON.parser(msg.obj.toString(), WxPayModel.class);
                if (wxResult == null) {
                    return true;
                }
                if (checkLoginStatus(wxResult)) {
                    WxPayModel wxModel = wxResult.getResult();
                    if (wxModel == null) {
                        return true;
                    }
                    OrderPayBean pay = new OrderPayBean(wxModel);
                    orderId = wxModel.getOrderId();
                    handleWxpay(pay);
                } else {
                    showToast(wxResult.getMessage());
                }
                return true;
            //支付宝支付回调
            case MsgID.courier_aliPay:
                cancelLoadingDialog();
                ReqResult<?> aliResult = JSON.parserMap(msg.obj, String.class);
                if (aliResult.getResult() == null) {
                    showToast("服务器异常");
                    return true;
                }
                if (checkLoginStatus(aliResult)) {
                    orderId = aliResult.getResultMap().get("orderId") + "";
                    alipay(aliResult.getResultMap().get("payInfo") + "");
                    alipay(aliResult.getResult().toString());
                } else {
                    showToast(aliResult.getMessage());
                }
                return true;
            //微信或支付宝支付成功后回调
            case MsgID.wxPayCallback:
                cancelLoadingDialog();
                final ReqResult<?> wxReqResult = JSON.parser(msg.obj);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(wxReqResult)) {
                            UserBean userBean = AppCache.getUser();
                            if (userBean != null) {
                                userBean.setState(Const.CourierRegisterStatus.RegisterOkStatus);
                                userBean.setIsJam(1);
                                UserBean.CourierAudit courierAudit = userBean.getCourierAudit();
                                if (courierAudit == null) {
                                    courierAudit = new UserBean.CourierAudit();
                                }
                                courierAudit.setReceiveStatus(2);
                                userBean.setCourierAudit(courierAudit);
                                AppCache.setUser(userBean);
                            }
                            setResult(Activity.RESULT_OK);
                            startActivity(RegisterCourierOpenedSuccessfulActivity.class);
                            finish();
                        } else {
                            showToast(wxReqResult.getMessage());
                        }
                    }
                });
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    /**
     * 处理跳转到微信支付
     *
     * @param pay
     */
    private void handleWxpay(OrderPayBean pay) {
        if (pay == null) {
            Toast.makeText(this, "订单数据异常", Toast.LENGTH_SHORT).show();
        } else {
            sendPayReq(pay);
        }
    }

    private void sendPayReq(OrderPayBean pay) {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(pay.getAppid());
        //
        PayReq req = new PayReq();
        if (getIntent() != null) {
            String isCollect = getIntent().getStringExtra("isCollect");
            if (isCollect != null) {
                req.extData = isCollect;
            }
        }
        req.appId = pay.getAppid();
        req.partnerId = pay.getPartnerid();
        req.prepayId = pay.getPrepayid();
        req.packageValue = pay.getPackageValue();
        req.nonceStr = pay.getNoncestr();
        req.timeStamp = pay.getTimestamp();
        req.sign = pay.getSign();
        //
        msgApi.sendReq(req);
    }

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void alipay(final String payInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(RegisterMaterialPayActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mPayHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mPayHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    // String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(RegisterMaterialPayActivity.this, "支付成功!", Toast.LENGTH_SHORT).show();
                        showLoadingDialog(null);
                        AppHttp.getInstance().courierPayCallBack(orderId, 2);
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(RegisterMaterialPayActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                        }
                        // 6001代表支付取消
                        if (TextUtils.equals(resultStatus, "6001")) {

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(RegisterMaterialPayActivity.this, "支付失败，请重试！", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(RegisterMaterialPayActivity.this, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onDestroy() {
        if (wxCallBack != null) {
            unregisterReceiver(wxCallBack);
        }
        super.onDestroy();
    }
}
